var hArr=[],   //存的数组高度
	count = 0; //从哪里开始加载
    num = 36;  //要加载的数量
    cols = 0;      //列数
	
window.onload = function(){
	$.get("../PageListen","opr=onload&page=play");  //请求记录会话信息
	$.getJSON('../MusicManager',"opr=lists&start="+count+"&num="+num,callBack); //请求加载数据,请求36首音乐信息	 
}

window.onscroll = function(){
	//如果能够加载数据
	if(canLoad()){
		num = 12; //后面每次要加载的数量都是12
		$.getJSON('../MusicManager',"opr=lists&start="+count+"&num="+num,callBack);
	}
}

function canLoad(){
	var oBoxs = document.getElementsByClassName("box");
	var lastH = oBoxs[oBoxs.length-1].offsetTop + Math.floor(oBoxs[oBoxs.length-1].clientHeight/2-50);
	var scrollDis = document.documentElement.clientHeight + document.documentElement.scrollTop || document.body.clientHeight+document.body.scrollTop;
	return lastH<scrollDis?true:false;
}

function callBack(data){
	console.log(data,data.length);
	for(var key in data){
		$("#main").append('<div class="box">'+
				'<div class="pic">'+
				'<img src="'+data[key].purl+'" onerror='+"this.src='../images/p1.jpg'"+'>'+
				'<p><a href="#" title='+data[key].mname+' data-con = '+data[key].mid+'>'+data[key].mname+'</a></p>'+
				'<p>'+data[key].sname+'</p></div></div>');
	}
	if(count == 0){
		init();     //第一次以后,就完成初始化,其他时候不管,第一次的num为36,其余时候都是12
	}
	layout();
}

$("#main").on('click','a',function(){
	/*alert($(this).attr('title')+$(this).html());*/
	console.log($(this).attr("title"),$(this).attr('data-con'));
	$.get('../MusicPlay','mid='+$(this).attr('data-con'),test,"text");
	return false;
})

function test(data){
	console.log("返回回来的数据:"+data);
	var objWin = null;
	if(data == "no"){
		 objWin = window.open("musicplay.html");
		 var loop = setInterval(function(){
			 //监听打开的页面是否被关闭的事件,如果已经被关闭的话就重新发送ajax请求将会话删除掉
			 if(objWin.closed){
				 clearInterval(loop);
				 $.get("../PageListen","opr=del&page=music");
			 }
		 },2000);
	}
	localStorage.setItem('demo',new Date());
}

function init(){
	var width = Math.floor($(".box").innerWidth()),
		bWidth = $(window).width();
		cols = Math.floor(bWidth/width);
		cols = cols>6? 6 : cols;  //最多6列
		console.log("初始化的数据为:"+width,bWidth,cols);
	$("#main").css({"width":width*cols+'px',"margin":"auto"});    
}

function layout() {
	var oBoxs = document.getElementsByClassName('box');
	for(var i= 0;i< oBoxs.length ;i++){
		var h = Math.floor(oBoxs[i].offsetHeight);
		if(i<cols){
			hArr[i] = h;
		}else{
			var minH = Math.min.apply(null,hArr);
			var index = hArr.indexOf(minH);   //找到最小高度的那个索引
			oBoxs[i].style.position = "absolute";
            oBoxs[i].style.top = minH +'px';
            oBoxs[i].style.left = oBoxs[index].offsetLeft+'px';
			hArr[index] = minH + h;
		}
	}
	count = oBoxs.length ;
}


